import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from SecureHelperServer.settings import formatResponseData
from User.models import User
from utils.conf import Response
from utils.custom import MyJWTAuthentication


class SaveUserInfoView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        保存用户信息
        """
        data = copy.deepcopy(formatResponseData)
        try:
            username = request.data.get("username")
            email = request.data.get("email")
            gender = request.data.get("gender")
            birthday = request.data.get("birthday")
            headSculptureFile = request.FILES.get("headSculptureFile")

            if not (username and email and gender and birthday):
                return Response(data=data, responseMsg="信息未填写完整", loggerMsg="保存用户信息：信息未填写完整",
                                isError=True)

            user = request.user

            users = User.objects.exclude(uid=user.uid)
            if users.filter(username=username).exists():
                return Response(data=data, responseMsg="用户名已存在", loggerMsg="保存用户信息：用户名已存在",
                                isError=True)

            if users.filter(email=email).exists():
                return Response(data=data, responseMsg="邮箱已存在", loggerMsg="保存用户信息：邮箱已存在", isError=True)

            user.username = username
            user.email = email
            user.gender = gender
            user.birthday = birthday

            # 保存头像
            if headSculptureFile:
                imageType = headSculptureFile.name.split(".")[-1]
                fileName = user.uid + f".{imageType}"
                if user.headSculpture.name != "userHeadSculptures/default.png":
                    user.headSculpture.delete()
                user.headSculpture = headSculptureFile
                user.headSculpture.name = fileName

            user.save()

            return Response(data=data, responseMsg="保存成功", loggerMsg=f"保存用户信息: 成功，uid={user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
